<template>
	<view class="container">
		<u-form :model="form" ref="loginForm">
			<!-- 手机号 -->
			<u-form-item label="手机号" prop="phone">
				<u-input v-model="form.phone" placeholder="请输入手机号" type="number" />
			</u-form-item>
			<!-- 密码 -->
			<u-form-item label="密码" prop="password">
				<u-input v-model="form.password" placeholder="请输入密码" password />
			</u-form-item>
		</u-form>
		<!-- 登录按钮 -->
		<u-button type="primary" @click="handleLogin" :loading="loading" style="margin-top: 40rpx">立即登录</u-button>
		<!-- 跳转注册 -->
		<view class="footer">
			<text @click="navigateToRegister">没有账号？立即注册</text>
		</view>
	</view>
</template>

<script>
import {login} from '../login/loginApi'
export default {
	data() {
		return {
			// 登录表单
			form: {
				phone: '',
				password: ''
			},
			loading: false,
			// 校验规则
			rules: {
				phone: [
					{
						required: true,
						message: '请输入手机号',
						trigger: ['blur', 'change']
					},
					{
						validator: (rule, value) => /^1[3-9]\d{9}$/.test(value),
						message: '手机号格式不正确',
						trigger: ['blur']
					}
				],
				password: [
					{
						required: true,
						message: '请输入密码',
						trigger: ['blur', 'change']
					},
					{
						min: 6,
						max: 20,
						message: '密码长度6-20位',
						trigger: ['blur']
					}
				]
			}
		};
	},
	onReady() {
		// 兼顾wx小程序的校验规则
		this.$refs.loginForm.setRules(this.rules);
	},
	methods: {
		// 登录
	async handleLogin() {
			// 调用登录接口
			const res= await login(this.form.phone, this.form.password);
			if (res.code===200) {
				// 登录成功
				console.log("登录成功",res);
				
				uni.setStorageSync('elderId', res.data.elderId);
				uni.setStorageSync('phone', res.data.phone);
				uni.setStorageSync('elderName', res.data.name);
				uni.setStorageSync('elderGender', res.data.gender);
				uni.setStorageSync('elderIdCard', res.data.idCard);
				uni.showToast({
					title: '登录成功',
					icon: 'none'
				});
				// 跳转首页
				uni.switchTab({
					url:'/pages/healthManage/healthManage'
				})
			}else if (res.message == "密码错误") {
				uni.showToast({
					title: '密码错误',
					icon: 'none'
				});
			}else if (res.message == "该账户尚未注册") {
				uni.showToast({
					title: '该号码未注册',
					icon: 'none'
				});
			}
		},
		// 跳转注册
		navigateToRegister() {
			uni.navigateTo({ url: '/pages/register/register' });
		}
	}
};
</script>

<style lang="less" scoped>
.container {
	padding: 40rpx;

	.footer {
		margin-top: 40rpx;
		text-align: center;
		color: #2979ff;
		font-size: 28rpx;
	}
}
</style>
